package com.gwnet.rider.service.impl;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gwnet.common.bean.vo.LoginVO;
import com.gwnet.common.config.WxConfig;
import com.gwnet.common.core.exception.base.BaseException;
import com.gwnet.common.core.exception.user.UserException;
import com.gwnet.common.satoken.utils.LoginHelper;
import com.gwnet.rider.domain.RiderUser;
import com.gwnet.rider.domain.bo.RiderUserLoginBO;
import com.gwnet.rider.domain.vo.RiderTokenVO;
import com.gwnet.rider.enums.RiderStatusEnum;
import com.gwnet.rider.mapper.RiderUserMapper;
import com.gwnet.rider.service.RiderLoginService;
import com.gwnet.shop.utils.StringUtils;
import com.gwnet.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 骑手登录
 * @author: WangLiang
 * @date: 2024/7/30 9:45
 */
@Slf4j
@Service
public class RiderLoginServiceImpl implements RiderLoginService {


    private final RiderUserMapper riderUserMapper;
    private final WxConfig wxConfig;

    @Autowired
    public RiderLoginServiceImpl(RiderUserMapper riderUserMapper, WxConfig wxConfig) {
        this.riderUserMapper = riderUserMapper;
        this.wxConfig = wxConfig;
    }


    /**
     * 根据账号密码登录
     * @param loginBO
     * @return
     * @throws WxErrorException
     */
    @Override
    public LoginVO loginByAccount(RiderUserLoginBO loginBO) throws WxErrorException {
        WxMaJscode2SessionResult session = getSession(loginBO.getCode());
        // 验证登录名和密码 前端加密 + 后端继续加密  ==》  比对 ==》 成功登录 ==》 绑定openID ==》响应登录
        // 根据用户名查询用户信息
        LambdaQueryWrapper<RiderUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RiderUser::getPhone,loginBO.getAccount());
        List<RiderUser> oldUserList = riderUserMapper.selectList(queryWrapper);
        if(oldUserList.size() > 0){
            RiderUser riderUser = oldUserList.get(0);
            boolean check = BCrypt.checkpw(loginBO.getPassword(), riderUser.getLoginPassword());
            if(!check){
                throw new BaseException("用户名或者密码不正确");
            }
            // 是否被禁用 状态 1 正常 0 无效
            if(riderUser.getStatus().equals(0)){
                throw new UserException("user.blocked",riderUser.getPhone());
            }
            // 绑定openId到骑手账号上
            riderUser.setBizUserId(session.getOpenid());
            riderUser.setBizUnionid(session.getUnionid());
            riderUser.setBizTempSession(session.getSessionKey());
            riderUserMapper.updateById(riderUser);
            LoginVO loginVO = buildRiderLoginVO(riderUser);
            return loginVO;
        } else {
          throw new UserException("user.not.exists",loginBO.getAccount());
        }
    }

    /**
     * 根据微信code登录/绑定
     * @param code
     * @return
     * @throws WxErrorException
     */
    @Override
    public LoginVO loginByCode(String code) throws WxErrorException {

        WxMaJscode2SessionResult session = getSession(code);
        // 根据openId查询用户信息
        String openid = session.getOpenid();
        LambdaQueryWrapper<RiderUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RiderUser::getBizUserId,openid);
        List<RiderUser> userList = riderUserMapper.selectList(queryWrapper);
        if(userList.size() > 0){
            RiderUser riderUser = userList.get(0);

            if(riderUser.getStatus().equals(RiderStatusEnum.RESIGNATION.code())){
                throw new BaseException("您已离职，无法登录");
            }else if(riderUser.getStatus().equals(RiderStatusEnum.DISABLE.code())){
                throw new BaseException("您的账号已被禁用，无法登录");
            }

            // 更新sessionKey
            riderUser.setBizTempSession(session.getSessionKey());
            riderUser.setBizUnionid(session.getUnionid());
            riderUserMapper.updateById(riderUser);
            LoginVO loginVO = buildRiderLoginVO(riderUser);
            return loginVO;
        }
        return null;
    }

    @Override
    public LoginVO buildRiderLoginVO(RiderUser riderUser) {
        // 生成token
        LoginUser loginUser = buildLoginUser(riderUser);
        SaLoginModel model = new SaLoginModel();
        LoginHelper.login(loginUser,model);

        LoginVO loginVO = new LoginVO();
        loginVO.setAccessToken(StpUtil.getTokenValue());
        loginVO.setExpireIn(StpUtil.getTokenTimeout());
        loginVO.setOpenid(riderUser.getBizUserId());
        loginVO.setUserId(riderUser.getRiderId());
        return loginVO;
    }

    private LoginUser buildLoginUser(RiderUser riderUser){
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(riderUser.getRiderId());
        loginUser.setUsername(riderUser.getRiderName());
        // UserType.APP_USER.getUserType()  = app_user
        loginUser.setUserType("app_rider_user");
        return loginUser;
    }

    /**
     * 根据微信code获取session
     * @param code
     * @return
     * @throws WxErrorException
     */
    private WxMaJscode2SessionResult getSession(String code) throws WxErrorException {
        // 根据code获取openID;
        String recode = code.replaceAll("\"","");
//        WxMaJscode2SessionResult session = wxConfig.getWxMaRiderService().getUserService().getSessionInfo(recode);

        // 假设已经登录成功
        WxMaJscode2SessionResult session = new WxMaJscode2SessionResult();
        session.setOpenid("XJ3KXAABC1eH5bxyzqNo5N2R1HJi");
        session.setSessionKey("gTyMXrVs2CzZNhZmjl6ZTZ==");
        session.setUnionid("HIJKLo1A3sF6G74s5d8E5A0B8D2B3H8");

        return session;
    }
}
